package response

import (
	"carSpider/data"
	goSpider "github.com/Flyits/goSpider/src"
	"github.com/antchfx/htmlquery"
	"strings"
)

const BaseUrl = "https://car.m.yiche.com"
const ImgBaseUrl = "https://photo.m.yiche.com/car/"

func Brand(response goSpider.Response, spider *goSpider.Spider) {
	letterList := htmlquery.Find(response.HtmlNode, "//div[@class='brand-content']//dl")
	brandItem := data.Brand{}
	for _, letter := range letterList {
		brandItem.FirstLetter = htmlquery.FindOne(letter, ".//dt/text()").Data
		for _, brand := range htmlquery.Find(letter, ".//dd") {
			brandItem.Name = htmlquery.FindOne(brand, ".//p/text()").Data
			brandItem.Logo = htmlquery.SelectAttr(htmlquery.FindOne(brand, ".//img"), "data-original")
			brandItem.Logo = strings.Replace(brandItem.Logo, "_4", "_8", -1)
			modelUrl := htmlquery.SelectAttr(htmlquery.FindOne(brand, ".//a"), "href")
			modelUrl = BaseUrl + modelUrl
			spider.AddJob(goSpider.UrlItem{
				Url:         modelUrl,
				HandlerFunc: Model,
				Attach:      brandExists(brandItem),
			})
		}
	}
}

// 检测数据是否存在
func brandExists(result data.Brand) int {
	brand := data.Brand{}
	data.Db.Where("name = ?", result.Name).First(&brand)
	if data.Db.NewRecord(brand) {
		data.Db.Create(&result)
		return result.ID
	}
	return brand.ID
}
